<template>
	<div class="table-view-public-data">
        <div class="container" v-if="!waiting">
            <div class="table-wrapper">
				<g-scrollbar class="table-wrapper-scrollbar">
	                <div class="table-container">
                    	<table>
	                        <thead>
	                            <tr>
	                                <th><div>#</div></th>
									<table-view-title-row v-for="(field, i) in fieldsList"
										:key="i"
										:field-index="i"
										:field-name="field.name"
										:field-type="field.type"
										:index-exist="field.indices.length > 0"
										:reset-exception="resetException"
                                        :is-private="isPrivate"
										@sort-by-field="getDataset"
										@reset-other-field-icon="resetOtherFieldIcon">

									</table-view-title-row>

	                            </tr>

	                        </thead>

	                        <tbody>

	                            <tr v-for="(item, index) in items" :key="index">
	                                <td>
	                                    {{item.id}}
	                                </td>
	                                <td v-for="(field, idx) in fieldsList" :key="idx"
										v-bind:class="{ 'align-right': (field.type === 'double' ||
											field.type === 'long' || field.type === 'integer')}">
	                                    {{item.attrs[field.name]}}
	                                </td>
	                            </tr>

	                        </tbody>
	                    </table>
	                </div>
				</g-scrollbar>

                <div class="table-loading" v-show='loading'>
                    <i class="iconfont icon-loading icon-spin"></i>
                </div>
            </div>

            <div class="flip-wrapper" v-if="hasNext || page > 0">
                <div class="flip-container" >

                    <span>共 {{previewData.count}} 条</span>
                    <span>
                        第 <input class="page" type="text" v-model.trim="displayPage" @input="validation($event)" :disabled="loading" @blur="toPage" @keyup.enter="toPage"> 页
                    </span>
                    <span>共 {{totalPage}} 页</span>
                    <span :class="{'hide': previewData.count < limit}">
                        <button class="flip" :class="{'disable': page==0 || loading }" :disabled="page==0 || loading" @click="getDataset({page: page-1, sortField: sortField, sortType:sortType})">
                            <i class="iconfont icon-caret-left"></i>
                        </button>
                        <button class="flip" :class="{'disable': !hasNext || loading}" :disabled="!hasNext || loading" @click="getDataset({page: page+1, sortField: sortField, sortType:sortType})">
                            <i class="iconfont icon-caret-right"></i>
                        </button>
                    </span>

                </div>
            </div>
        </div>

        <div class="container" v-else>
            <div class="waiting">
                <div v-if="resultStatus === 'empty'">无属性数据</div>
                <div v-else-if="resultStatus === 'error'">获取数据失败</div>
                <i v-else class="iconfont icon-loading icon-spin"></i>
            </div>
        </div>

	</div>
</template>

<script>

    import axios from 'axios'
    import qs from 'qs'
	import Bus from '../../utils/event_bus'
	import GScrollbar from '../common/g-scrollbar'
	import TableViewTitleRow from './table-view-title-row'

	const ERR_CREATE_INDEX = '建立索引失败';
	const ERR_REQUEST_DATA = '请求数据失败';
	const SUCCESS_CREATE_INDEX = '创建索引成功';

    var axiosInstance = axios.create();
    export default {

        name: 'table-view',

		components: {
			TableViewTitleRow,
			GScrollbar
		},

        data: function() {
            return {
                limit: 25,
                page: 0,
                displayPage: 1,
                fields: undefined,
                items: undefined,
                hasNext: '',
                loading: false,
                waiting: true,
                resultStatus: '',
				resetException: '',	// 重置排序按钮例外情况，即不重置的字段
				sortField: '',		// 默认排序字段
				sortType: 'DESC',	// 默认排序类型
				fieldsList: null,	// 字段信息列表
            }
        },

        props: {
            previewData: Object,
            isPrivate: Boolean
        },

        mounted: function() {

			this.getFieldsInfo();
            this.getDataset();

        },

		created: function() {

			/**
			 * 监听建立索引事件
			 */
			Bus.$off('create-index');
			Bus.$on('create-index', (field, fieldIndex) => {

				this.createIndex(field, fieldIndex);

			});

		},

        computed: {
            totalPage() {
                return Math.ceil(this.previewData.count/this.limit);
            }
        },

        methods: {

			/**
			 * 标记失败
			 * @param string errorType 出错信息
			 */
			markError: function(errorType) {

				this.$message.error(errorType);
				this.loading = false;
				this.resultStatus = 'error';
				return;

			},

			/**
			 * 检查用户输入的跳转至页码
			 */
            validation: function(e) {

                let displayPage = this.displayPage;

                this.displayPage = parseInt(displayPage.replace(/[^0-9]/g, ''));

                if (this.displayPage === 0) {
                    this.displayPage += 1;
                }

                if (this.displayPage > this.totalPage) {
                    this.displayPage = this.totalPage;
                }

            },

			/**
			 * 跳转至用户指定的页码
			 */
            toPage: function() {

                this.displayPage = this.displayPage || 1;

				this.getDataset({
					page: this.displayPage - 1,
					sortField: this.sortField,
					sortType: this.sortType
				});

            },

			/**
			 * 获取对指定字段进行排序的结果集
			 * @param string field 字段名称
			 */
			getDataset: function(options) {

				if (!options) {
					options = {};
				}

				let uid = this.previewData.uid;
				let type = this.isPrivate ? 'data' : 'public_data';
				let params = {};

				if ('sortField' in options) {
					this.sortField = options['sortField'];
				}

				if ('sortType' in options) {
					this.sortType = options['sortType'];
				}

				for (var key in options) {
					params[key] = options[key];
				}

				if (!('page' in params)) {
					this.page = 0;
				} else {
					this.page = (params['page'] > 0) ? params['page'] : 0;
				}

				if (!('limit' in options)) {
					params['limit'] = this.limit;
				}

				if (!('offset' in options)) {
					params['offset'] = this.page * this.limit;
				}

				if (!('returnGeometry' in options)) {
					params['returnGeometry'] = false;
				}

				this.loading = true;

                if(this.isPersonalApplyData()){
                    type = 'public_data';
                }

				axiosInstance.post(`/s/${type}/${uid}/query`, qs.stringify(params))
                .then((res) => {
                    // console.log(type, res);
                   
                    if(res.data.code != 0){
                        this.markError(ERR_REQUEST_DATA);
                        return;
                    }

                    let data = res.data.data;
                    let featureLength = data.features.length;

                    if(featureLength === 0){
                        this.resultStatus = 'empty';
                        this.loading = false;
                        this.waiting = false;
                        return
                    }

                    this.fields = data.fields;
                    this.items = data.features;

                    this.hasNext = !!(featureLength >= this.limit);

                    this.loading = false;
                    this.waiting = false;

                })
                .catch((error) => {

                    this.markError(ERR_REQUEST_DATA);
                    return;

                });
			},

			/**
			 * 重置排序按钮
			 * @param string field 重置例外
			 */
			resetOtherFieldIcon: function(field) {

				this.resetException = field;

			},

			/**
			 * 获取字段类型和是否建立索引信息
			 */
			getFieldsInfo: function() {

				let params = {};
				let type = this.isPrivate ? 'data' : 'public_data';
				let uid = this.previewData.uid;
				params.limit = this.limit;
				params.offset = this.page * this.limit;
				params.returnGeometry = false;
               
                if(this.isPersonalApplyData()){
                    type = 'public_data';
                }

				axiosInstance.post(`/s/${type}/${uid}/fields`, qs.stringify(params))
                .then((res) => {
                    // console.log(res);
                    if(res.data.code != 0){
                        this.markError(ERR_REQUEST_DATA);
                        return;
                    }

                    this.fieldsList = res.data.data;

                })
                .catch((error) => {

                    this.markError(ERR_REQUEST_DATA);
                    return;

                });

			},

			/**
			 * 依据字段建立索引
			 * @param string field 字段名称
			 */
			createIndex: function(field, fieldIndex) {

				let self = this;
				let requestUrl = `/s/data/${this.previewData.uid}/${field}/index`;
				let params = {};

				axiosInstance.post(requestUrl, qs.stringify(params))
				.then((res) => {

					if (res.data.code !== 0) {
						self.markError(ERR_CREATE_INDEX);
                        return;
					}

					this.fieldsList[fieldIndex].indices.push('default');

					this.$message.success('创建索引成功');

				}).catch((err) => {

					this.markError(ERR_CREATE_INDEX);
                    return;

				});

            },
            isPersonalApplyData(){
                let data_nav_key = this.$store.state.data_nav_key;
                let dom = document.querySelector('.private-upload-res');
                let flag = false;
                if(dom){
                    flag = dom.classList.contains('active');
                }
                if(data_nav_key == 'private-data' && !flag){
                    return true;
                }
                return false;
            }
        },

        watch: {
            page: function() {
                this.displayPage = this.page + 1;
            }
        }
    }
</script>

<style lang="scss" rel="stylesheet/scss">

     @import "common";

    .table-view-public-data{
        
        color: rgba(0,0,0, .65);
        @include absolute(48px, 10px, 10px, 10px);
        z-index: 10;
        font-size: 12px;
        // border: 1px solid #eee;
        background: $bgWhite;
        overflow: hidden;

		.g-scrollbar .g-scrollbar-wrapper {
			width: calc(100% - 10px) !important;
			height: calc(100% - 10px) !important;
		}

        div{
            @include box-sizing(border-box);
        }

        .container{

            height: 100%;
            width: 100%;

            .table-wrapper {

                height: calc(100% - 46px);

                .table-loading{
                    position: absolute;
                    top: 0;
                    background: rgba(255,255,255, .3);
                    height: 100%;
                    width: 100%;
                    overflow: hidden;
                    text-align: center;
                    font-size: 20px;

                    >i{
                        position: absolute;
                        top: 42%;
                    }
                }


				.table-wrapper-scrollbar {

					height: 100%;
					width: 100%;

					.table-container{
						overflow-y: hidden;
						overflow-x: hidden;
						height: 100%;
						width: calc(100% + 15px);

						table{

							border-collapse: collapse;
							min-width: calc(100% - 15px);

							thead{

								background-color: $bgPrimary;
								font-weight: 400;

								th {
									border: 1px solid $bdGray;
								}

							}

							tbody{

								td{
									height: 28px;
									text-align: left;
									line-height: 28px;
									border-collapse: collapse;
									white-space:nowrap;
									padding: 0 8px;
									border: 1px solid $bdGray;
									min-width: 100px;
									max-width: 280px;
									text-overflow: ellipsis;
									overflow: hidden;
								}

								td:nth-child(1) {
									text-align: center;
									min-width: 12px;
								}

								td.align-right {
									text-align: right;
								}

							}
						}

					}
                }
            }

            .flip-wrapper{
                height: 46px;
                width: 100%;
                padding: 12px;
                text-align: center;

                .flip-container{

                    overflow: hidden;

                    >span {
                        height: 22px;
                        margin: 0 8px;
                        line-height: 20px;
                    }

                    .hide{
                        display: none;
                    }

                    .page{
                        width: 32px;
                        height: 20px;
                        line-height: 20px;
                        padding: 2px 4px;
                        border: 1px solid #e6e9f0;
                        text-align: center;
                        border-radius: $bdRadius;
                    }

                    .flip{
                        cursor: pointer;
                        border-radius: $bdRadius;
                        color: $gray;
                        font-size: 12px;
                        line-height: 22px;
                        margin: auto;
                        text-align: center;
                        white-space: nowrap;
                        vertical-align: middle;
                        width: 22px;
                        height: 22px;
                        border: 1px solid $bdGray;
                        background-color: transparent;

                        &:hover{
                            border: 1px solid darken($bdGray, 10%);
                        }

                        &.disable{
                            cursor: not-allowed !important;
                        }
                    }
                }
            }

            .waiting {

                width: 100%;
                position: relative;
                text-align: center;
                top: calc(50% - 30px);

                >div {
                    color: $dark;
                    font-size: $fontSizeBase;
                }

                >i{
                    font-size: 20px;
                    line-height: 20px;
                }
            }
        }


    }
</style>
